#!/usr/bin/env python
# -*- coding=utf-8 -*-
import sys
import os
from collections import defaultdict

class TitleParser():
    """
    Reading in a file title and than getting indicated column element.
    Title names are all CaseIgnore
    """
    
    def __init__(self,title):
        self.title_list = [i.lower() for i in title.strip().split('\t')]

    def get_field(self,line_list,colname,check=True):
        """
        Reading in a list and returning the element with the 
        index which colname in title's list
        """
        if check:
            if len(self.title_list) != len(line_list):
                raise Exception("Title length differs with line!")
        try:
            idx = self.title_list.index(str(colname).lower())
        except:
            print('{colname} not in title！'.format(colname=colname))
            return None

        return line_list[idx]

    def have_title(self,colname):
        """
        Judging whether a colname is in title
        """
        if str(colname).lower() in self.title_list:
            return True
        return False
    
    def get_idx(self,colname):
        """
        return index of columns by their name in title list
        """
        idx = self.title_list.index(str(colname).lower())

        return idx

def sample_info_parse(sample_info):
    """
    parse sample info
    info_dict {
        'familyid':{
            sample1:[info],
            sample2:[info],
            ...
        }
    }
    """
    info_dict = defaultdict()
    with open(sample_info,'r') as indata:
        for line in indata:
            if line.lower().startswith('#familyid'):
                title = line
                tp = TitleParser(title)
            elif line.lower().startswith('#'):
                pass
            else:
                line_list = line.strip().split("\t")
                familyid = tp.get_field(line_list,"#familyid")
                sampleid = tp.get_field(line_list,"sampleid")
                if familyid not in info_dict:
                    info_dict[familyid] = {}
                    info_dict[familyid][sampleid] = [line_list]
                else:
                    if sampleid not in info_dict[familyid]:
                        info_dict[familyid][sampleid] = [line_list]
                    else:
                        print('Duplicate sample {sampleid}!'.format(sampleid=sampleid))
    return info_dict                       

def output_share_temp(infile,basic_dir,info_dict):
    """
    output share template by familyid only adapted for all member 
    are patients in family
    """
    for familyid in info_dict:
        samples = list(info_dict[familyid])
        cases = ",".join(samples)
        ofile = "{familyid}.share.site.xls".format(familyid=familyid)
        oshell = os.path.join(basic_dir,"{familyid}/{familyid}.share.sh".format(
            familyid=familyid))
        share_template = """
        python /ifs/TJPROJ3/DISEASE/share/Disease/Varition/Filter/CompareCaseControl.py \\
            -in {infile} \\
            -t site \\
            -sL {cases} -sf 1 \\
            -o {basic_dir}/{familyid}/{ofile}
        """.format(**locals())

        with open(oshell,'w') as odata:
            odata.write(share_template)
    print('shell generation completion!')

if __name__ == "__main__":
    sample_info = sys.argv[1]
    basic_dir = sys.argv[2]
    infile = sys.argv[3]
    info_dict = sample_info_parse(sample_info)
    output_share_temp(infile,basic_dir,info_dict)
